package datastructure.work;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

/**
 * @Author Gan
 * @Date 2021/5/11 18:53
 * @Description: 2, 请设计一个猜数字小游戏，可以试玩5次。试玩结束之后，给出提示：游戏试玩结束，
 * 请付费。(要求即使把程序重启也总共只能猜5次)
 * (Properties: 读取和存文件记录猜数字次数)
 */
public class DemoWork1 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        FileReader fr = new FileReader("log.txt");
        //读取游戏的次数
        properties.load(fr);
        fr.close();
        int count;
        //获取count的value,count是已经玩过的次数
        String value = properties.getProperty("count");
        if (value == null)
            count = 0;
        assert value != null;
        count = Integer.parseInt(value);
        //若log.txt文件中count为null则赋初值0
        //判断次数是否大于5
        if (count > 5) {
            //log.txt中count值大于5直接结束
            System.out.println("试玩已结束，请付费！");
            System.exit(0);
        } else {
            properties.setProperty("count", String.valueOf(++count));
            FileWriter fw = new FileWriter("log.txt");
            properties.store(fw, "guessNumber");
            fw.close();
            GuessNumber.start();
        }
    }
}

class GuessNumber{
    private GuessNumber() {
    }
    public static void start(){
        int count = 0;
        int num = (int) (Math.random() * 100 + 1);
        System.out.println("请输入你猜测的数字：");
        Scanner scan = new Scanner(System.in);
        while (true) {
            int n = scan.nextInt();
            count++;
            if (count > 3){
                System.out.println("猜了三次还没中，放弃吧！");
                return;
            }
            if (n == num) {
                System.out.println("恭喜你，猜中了！");
                break;
            } else if (n > num) {
                System.out.println("猜大了！");
            } else {
                System.out.println("猜小了！");
            }
        }
    }
}
